package com.yzh.grainmall.product.exception;

import com.yzh.grainmall.common.exception.BizCodeEnum;
import com.yzh.grainmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yuzhen
 * @create 2021-06-05 14:55
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.yzh.grainmall.product.controller")
public class GrainmallExceptionControllerAdvice {

    //告诉mvc 这个方法能处理什么异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", errorMap);
    }

    //    不行的话 来到这个最大的异常处理 能处理任意类型的异常
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {
        log.error("错误：", e);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }


}
